# 数据库服务类
import logging
from app.utils.mysql_helper import MySQLHelper

class DatabaseService:
    def __init__(self):
        self.mysql_helper = MySQLHelper(auto_commit=True)
        self.logger = logging.getLogger(__name__)
    
    def execute_query(self, query, params=None):
        """执行SQL查询"""
        try:
            result = self.mysql_helper.execute_query(query, params)
            self.logger.info(f"查询成功，返回 {len(result)} 条记录")
            return {
                "success": True,
                "data": result,
                "message": "查询成功"
            }
        except Exception as e:
            self.logger.error(f"查询失败: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "message": "查询失败"
            }
    
    def execute_update(self, query, params=None):
        """执行SQL更新操作"""
        try:
            result = self.mysql_helper.execute_update(query, params)
            self.logger.info("更新操作成功")
            return {
                "success": True,
                "message": "更新成功"
            }
        except Exception as e:
            self.logger.error(f"更新失败: {str(e)}")
            return {
                "success": False,
                "error": str(e),
                "message": "更新失败"
            }
    
    def __del__(self):
        """析构函数，确保连接关闭"""
        try:
            if hasattr(self, 'mysql_helper'):
                self.mysql_helper.close()
        except:
            pass